// ...existing code...
package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"library-management/handlers"
)

func main() {
	db, err := gorm.Open(sqlite.Open("library.db"), &gorm.Config{})
	if err != nil {
		panic("无法连接数据库")
	}

	db.AutoMigrate(&handlers.Book{}, &handlers.User{}, &handlers.BorrowRecord{})

	r := gin.Default()

	r.Static("/static", "./static")

	// book CRUD & search
	r.GET("/api/books", handlers.GetBooks(db))
	r.POST("/api/books", handlers.CreateBook(db))
	r.GET("/api/books/:id", handlers.GetBook(db))
	r.PUT("/api/books/:id", handlers.UpdateBook(db))
	r.DELETE("/api/books/:id", handlers.DeleteBook(db))
	r.GET("/api/books/search", handlers.SearchBooks(db))

	// user endpoints
	r.POST("/api/users/register", handlers.RegisterUser(db))
	r.PUT("/api/users/:id", handlers.UpdateUser(db))
	r.GET("/api/users", handlers.ListUsers(db))

	// borrow / return
	r.POST("/api/borrow", handlers.BorrowBook(db))
	r.POST("/api/return/:id", handlers.ReturnBook(db))
	r.GET("/api/borrow_records", handlers.GetBorrowRecords(db))

	// statistics
	r.GET("/api/stats/overview", handlers.Overview(db))
	r.GET("/api/stats/top-borrowed", handlers.TopBorrowed(db))

	r.GET("/", func(c *gin.Context) {
		c.File("./static/index.html")
	})

	r.Run(":8080")
}
